<?php

namespace app\api2\controller;

use \app\common\controller\Api;
use app\common\library\Token;
use fast\Random;
use \think\Validate;
use app\common\library\Sms;
use \think\Cache;


use \think\Db;


class Worker extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /*
     * 登录获取验证码
     *
     *
     * */
    public function getPhoneCode()
    {
        if ($this->request->isPost()) {
            $phone = $this->request->post('phone');

            if (!$phone || !Validate::regex($phone, "/^1[3-9]{1}[0-9]{9}$/")) {

                $this->error(__('手机号不正确'));
            }

            $worker = Db::table('fa_worker')
                ->where('mobile', $phone)
                ->find();

            if (!$worker) {

                $this->success('该手机号不存在', [], 201);
            }

            if ($worker['deletetime'] != null) {

                $this->success('您的账号已禁用', [], 201);
            }

            $result = Sms::txSend($phone);

            if (!$result) {

                $this->error('发送验证码失败', [], 201);

            }

            if ($result->SendStatusSet[0]->Code != 'Ok') {

                $this->error($result->SendStatusSet[0]->Message, [], 201);

            }

            $code = $result->SendStatusSet[0]->SessionContext;

            Cache::set($phone, $code, 300);

            $this->success('ok', [], 200);
        }

    }

    /*
     * 登录验证验证码
     *
     *
     * */
    public function checkCode()
    {
        if ($this->request->isPost()) {
            $phone = $this->request->post('phone');
            $code = $this->request->post('code');

            if (!$phone || !Validate::regex($phone, "/^1[3-9]{1}[0-9]{9}$/")) {

                $this->error(__('手机号不正确'));
            }

            $tmpCode = Cache::get($phone);

            if (!$tmpCode) {

                $this->success('验证码已失效，请重新获取', [], 201);

            }

            if ($tmpCode != $code) {

                $this->success('验证码不正确', [], 201);
            }


            $worker = Db::table('fa_worker')
                ->where('mobile', $phone)
                ->find();

            $token = Random::uuid();

            Token::set($token, $worker['id'], 7 * 24 * 3600);

            $this->success('ok', ['token' => $token, 'worker' => $worker], 200);

        }
    }
}